# include "dfxFileReader.h"

namespace DFX
{
    UInt64 FileReader::GetSize() const
    {
        return mFile->GetSize();
    }

    UInt64 FileReader::GetPosition() const
    {
        return mPosition;
    }

    UInt64 FileReader::GetBytesLeft() const
    {
        return mFile->GetSize() - mPosition;
    }

    void FileReader::Seek(UInt64 position)
    {
        mPosition = position;
    }

    bool FileReader::Eof()
    {
        return mPosition >= mFile->GetSize();
    }

    UInt64 FileReader::Read(void *buffer, UInt64 size)
    {
        UInt64 realSize = size > GetBytesLeft() ? GetBytesLeft() : size;

        memcpy(buffer, mFile->GetData() + static_cast<UInt32>(mPosition), 
            static_cast<UInt32>(realSize));

        return realSize;
    }

    const UInt8* FileReader::MapStream() const
    {
        return mFile->GetData();
    }

    const UInt8* FileReader::MapStreamFromCurrentPosition() const
    {
        return mFile->GetData() + mPosition;
    }

    const String FileReader::ReadLine()
    {
        const UInt32 MAX_LINE_WIDTH = 65535;
        Int8 buffer[MAX_LINE_WIDTH];

        const UInt8 *c = MapStreamFromCurrentPosition();

        Int8 *out = buffer;
        Int8 *end = buffer + MAX_LINE_WIDTH;

        while (!Eof() && out < end)
        {
            mPosition++;

            char ch = (*c++);

            if (ch == 13)
                continue;

            if (ch == 10)
                break;

            *out++ = ch;
        }

        *out = NULL;

        return String(buffer);
    }
}